<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgContentNewsletter_subscriber_Pro extends JPlugin {

  function plgContentNewsletter_subscriber_Pro( &$subject, $config ) {
    JPlugin::loadLanguage( 'plg_content_newsletter_subscriber_pro' );

    parent::__construct( $subject, $config );
  }
  
  public function onContentPrepare($context, &$row, &$params, $page = 0) {
    $this->onPrepareContent(&$row, &$params, $page);
  }

  function onPrepareContent(&$row, &$params, $page=0) {
    if (is_object($row)) {
        $text = &$row->text;
    }
    else {
      $text = &$row;
    }
		// Our Joomla! Version
		$jversion = new JVersion();
		$j15 = ($jversion->RELEASE == '1.5');


		$mainframe = JFactory::getApplication();


    if (JString::strpos($text, '{newsletter_subscriber_pro}') === false) {
      return true;
    }
    if ($j15 == true) {
      $plugin = & JPluginHelper::getPlugin('content', 'newsletter_subscriber_pro');
      $pluginParams = new JParameter($plugin->params);
    }

    $db =& JFactory::getDBO();

    if (!function_exists('MySendMail')) {
      include('administrator/components/com_nspro/lib.php');
    }
    
    if ($j15 == true) {
			// email parameters
			$recipient = $pluginParams->def('email_recipient', 'email@email.com');
			$subject = $pluginParams->def('subject', 'New subscription to your site!');
			$fromName = $pluginParams->def('from_name', 'Newsletter Subscriber');
			$fromEmail = $pluginParams->def('from_email', 'newsletter_subscriber@yoursite.com');

			if ($fromName == 'Newsletter Subscriber') {
				$fromName = $mainframe->getCfg('fromname');
			}
			if ($fromEmail == 'newsletter_subscriber@yoursite.com') {
				$fromEmail = $mainframe->getCfg('mailfrom');
			}

			$sendingWithSetEmail = $pluginParams->def('sending_from_set', true);

			// text parameters
			$myNameLabel = $pluginParams->def('name_label', 'Name:');
			$myEmailLabel = $pluginParams->def('email_label', 'Email:');
			$mailing_list_label = $pluginParams->def('mailing_list_label', 'Mailing Lists:');
			$buttonText = $pluginParams->def('button_text', 'Subscribe to Newsletter');
			$pageText = $pluginParams->def('page_text', 'Thank you for subscribing to our site.');
			$errorText = $pluginParams->def('errot_text', 'Your subscription could not be submitted. Please try again.');
			$noName = $pluginParams->def('no_name', 'Please write your name');
			$noEmail = $pluginParams->def('no_email', 'Please write your email');
			$invalidEmail = $pluginParams->def('invalid_email', 'Please write a valid email');
			$pre_text = $pluginParams->def('pre_text', '');

			// size & color parameters
			$nameWidth = $pluginParams->def('name_width', '20');
			$emailWidth = $pluginParams->def('email_width', '20');
			$buttonWidth = $pluginParams->def('button_width', '100');
			$thanksTextColor = $pluginParams->def('thank_text_color', '#FF0000');
			$errorTextColor = $pluginParams->def('error_text_color', '#FF0000');
			$form_layout = $pluginParams->def('form_layout', '0');
			$label_pos = $pluginParams->def('label_pos', '0');

			// file parameters
			$saveList = $pluginParams->def('save_list', true);
			$savePath = $pluginParams->def('save_path', 'mailing_list.txt');
			$saveFormat = $pluginParams->def('save_format', '%n (%e);');

			// url parameters
			$exact_url = $pluginParams->def('exact_url', true);
			$disable_https = $pluginParams->def('disable_https', false);
			$fixed_url = $pluginParams->def('fixed_url', true);
			$myFixedURL = $pluginParams->def('fixed_url_address', "");

			// anti spam parameters
			$enable_anti_spam = $pluginParams->def('enable_anti_spam', true);
			$myAntiSpamQuestion = $pluginParams->def('anti_spam_q', 'How many eyes has a typical person? (ex: 1)');
			$myAntiSpamAnswer = $pluginParams->def('anti_spam_a', '2');
			$anti_spam_position = $pluginParams->def('anti_spam_position', 0);

			// multiple list parameters
			$show_select_list = $pluginParams->def('show_select_list', true);
			$fixed_ids = $pluginParams->def('fixed_ids', '');

			// extra field parameters
			$field_list = $pluginParams->def('field_list', "0");
			$fixed_fields = $pluginParams->def('fixed_field_ids', "");
			$text_field_width = $pluginParams->def('text_field_width', "20");
			$textarea_field_rows = $pluginParams->def('textarea_field_rows', "3");
			$textarea_field_cols = $pluginParams->def('textarea_field_cols', "25");
			$swidth = $pluginParams->def('select_field_width', '135');

			// extra field constant
			$name_prefix = 'nsp_'; // for the plugin

			// class suffix
			$classSuffix = $pluginParams->def('class_suffix', '');
	  }
	  else {
      // email parameters
      $recipient = $this->params->get('email_recipient', 'email@email.com');
      $subject = $this->params->get('subject', 'New subscription to your site!');
      $fromName = $this->params->get('from_name', 'Newsletter Subscriber');
      $fromEmail = $this->params->get('from_email', 'newsletter_subscriber@yoursite.com');

      if ($fromName == 'Newsletter Subscriber') {
        $fromName = $mainframe->getCfg('fromname');
      }
      if ($fromEmail == 'newsletter_subscriber@yoursite.com') {
        $fromEmail = $mainframe->getCfg('mailfrom');
      }

      $sendingWithSetEmail = $this->params->get('sending_from_set', true);

      // text parameters
      $myNameLabel = $this->params->get('name_label', 'Name:');
      $myEmailLabel = $this->params->get('email_label', 'Email:');
      $mailing_list_label = $this->params->get('mailing_list_label', 'Mailing Lists:');
      $buttonText = $this->params->get('button_text', 'Subscribe to Newsletter');
      $pageText = $this->params->get('page_text', 'Thank you for subscribing to our site.');
      $errorText = $this->params->get('errot_text', 'Your subscription could not be submitted. Please try again.');
      $noName = $this->params->get('no_name', 'Please write your name');
      $noEmail = $this->params->get('no_email', 'Please write your email');
      $invalidEmail = $this->params->get('invalid_email', 'Please write a valid email');
      $pre_text = $this->params->get('pre_text', '');

      // size & color parameters
      $nameWidth = $this->params->get('name_width', '20');
      $emailWidth = $this->params->get('email_width', '20');
      $buttonWidth = $this->params->get('button_width', '100');
      $thanksTextColor = $this->params->get('thank_text_color', '#FF0000');
      $errorTextColor = $this->params->get('error_text_color', '#FF0000');
      $form_layout = $this->params->get('form_layout', '0');
      $label_pos = $this->params->get('label_pos', '0');

      // file parameters
      $saveList = $this->params->get('save_list', true);
      $savePath = $this->params->get('save_path', 'mailing_list.txt');
      $saveFormat = $this->params->get('save_format', '%n (%e);');

      // url parameters
      $exact_url = $this->params->get('exact_url', true);
      $disable_https = $this->params->get('disable_https', false);
      $fixed_url = $this->params->get('fixed_url', true);
      $myFixedURL = $this->params->get('fixed_url_address', "");

      // anti spam parameters
      $enable_anti_spam = $this->params->get('enable_anti_spam', true);
      $myAntiSpamQuestion = $this->params->get('anti_spam_q', 'How many eyes has a typical person? (ex: 1)');
      $myAntiSpamAnswer = $this->params->get('anti_spam_a', '2');
      $anti_spam_position = $this->params->get('anti_spam_position', 0);

      // multiple list parameters
      $show_select_list = $this->params->get('show_select_list', true);
      $fixed_ids = $this->params->get('fixed_ids', '');

      // extra field parameters
      $field_list = $this->params->get('field_list', "0");
      $fixed_fields = $this->params->get('fixed_field_ids', "");
      $text_field_width = $this->params->get('text_field_width', "20");
      $textarea_field_rows = $this->params->get('textarea_field_rows', "3");
      $textarea_field_cols = $this->params->get('textarea_field_cols', "25");
      $swidth = $this->params->get('select_field_width', '135');

      // extra field constant
      $name_prefix = 'nsp_'; // for the plugin

      // class suffix
      $classSuffix = $this->params->get('class_suffix', '');
	  }

		/// C O M P O N E N T   P A R A M E T E R S
		jimport('joomla.application.component.helper');
		if ($j15 == true) {  
			$cparams = JComponentHelper::getParams( 'com_nspro' );
			$component = JComponentHelper::getComponent( 'com_nspro' );
			$cparams = new JParameter( $component->params );
			// We're in Joomla 1.5 (hurray!)
			$blacklist = $cparams->get('blacklist', '');
			$confirmSub = $cparams->get( 'send_confirm', '1');
			$fromNameConfirm = $cparams->get('from_name_confirm', 'Newsletter Subscriber');
			$fromEmailConfirm = $cparams->get('from_email_confirm', 'newsletter_subscriber@yoursite.com');

			if ($fromNameConfirm == 'Newsletter Subscriber') {
				$fromNameConfirm = $mainframe->getCfg('fromname');
			}
			if ($fromEmailConfirm == 'newsletter_subscriber@yoursite.com') {
				$fromEmailConfirm = $mainframe->getCfg('mailfrom');
			}

			$subjectConfirm = $cparams->get('subject_confirm', 'Subscription Confirmation');
			$messageConfirm = $cparams->get('message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');

			$subjectConfirm = JText::_($subjectConfirm);
			$messageConfirm = JText::_($messageConfirm);
		}
		else {
			$cparams =& JComponentHelper::getParams('com_nspro');
			// We're in Joomla 1.6
			$blacklist = $cparams->getValue('data.params.blacklist', '');
			$confirmSub = $cparams->getValue('data.params.send_confirm', '1');
			$fromNameConfirm = $cparams->getValue('data.params.from_name_confirm', 'Newsletter Subscriber');
			$fromEmailConfirm = $cparams->getValue('data.params.from_email_confirm', 'newsletter_subscriber@yoursite.com');

			if ($fromNameConfirm == 'Newsletter Subscriber') {
				$fromNameConfirm = $mainframe->getCfg('fromname');
			}
			if ($fromEmailConfirm == 'newsletter_subscriber@yoursite.com') {
				$fromEmailConfirm = $mainframe->getCfg('mailfrom');
			}

			$subjectConfirm = $cparams->getValue('data.params.subject_confirm', 'Subscription Confirmation');
			$messageConfirm = $cparams->getValue('data.params.message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');

			$subjectConfirm = JText::_($subjectConfirm);
			$messageConfirm = JText::_($messageConfirm);
		}

    $separator = '';
    if ($form_layout === '0') {
      $br = '<br/>';
      $tr = '<tr>';
      $ctr = '</tr>';
      $td = '<td>';
      $tdcolspan = '<td colspan="2">';
      $ctd = '</td>';
      $table = '<table>';  
      $ctable = '</table>';
      $emptycell = '<td></td>';
			if ($j15 != true) {
        $tr = '<tr style="border: none;">';			
				$td = '<td style="border: none; padding: 2px;">';
				$tdcolspan = '<td colspan="2" style="border: none; padding: 2px;">';
				$emptycell = '<td style="border: none;"></td>';
			}      
      $separator = $ctd . $td;
      if ($label_pos == '1') {
        $separator = $br;
        $emptycell = '';
      }
    }
    else {
      $br = ' ';
      $tr = '';
      $ctr = '';
      $td = '<td>';
      $tdcolspan = '<td>';
      $ctd = '</td>';
      $table = '<table><tr>';          
      $ctable = '</tr></table>';
      $emptycell = '';
			if ($j15 != true) {		
				$td = '<td style="border: none; padding: 2px;">';
				$tdcolspan = $td;
			}        
      $separator = $ctd . $td;
    }

    // find URL to post.
    if ($fixed_url) {
      $url = $myFixedURL;
    }
    else {
      if (!$exact_url) {
        $url = JURI::current();
      }
      else {
        if (!$disable_https) {
          $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        }
        else {
          $url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        }
      }
    }
    
    $url = htmlentities($url, ENT_COMPAT, "UTF-8");

    $myError = "";
    $errors = 3;

    if (isset($_POST["nsp_name"])) {
      $errors = 0;
      if ($enable_anti_spam) {
        if ($_POST["nsp_anti_spam_answer"] != $myAntiSpamAnswer) {
          $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Wrong anti-spam answer') . '</span>' . $br;
        }
      }
      if ($_POST["nsp_name"] === "") {
        $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $noName . '</span>' . $br;
        $errors = $errors + 1;
      }
      if ($_POST["nsp_email"] === "") {
        $myError = $myError. '<span style="color: '.$errorTextColor.';">' . $noEmail . '</span>' . $br;
        $errors = $errors + 2;
      }
      if (($errors & 2) != 2) {
        if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", strtolower($_POST["nsp_email"]))) {
          $myError = $myError. '<span style="color: '.$errorTextColor.';">' . $invalidEmail . '</span>' . $br;
          $errors = $errors + 2;
        }
      }

      if (($errors & 2) != 2) {
        $blackarray = explode(';', $blacklist);

        foreach ($blackarray as $black_email) {
          if ($_POST["nsp_email"] == $black_email) {
            $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Your email has been blacklisted.') . '</span>' . $br;
            $errors = $errors + 2;
            break;
          }
        }
      }

      $vresult = ValidateExtraFields($_POST, true, $br, $errorTextColor, 'plugin');
      if ($vresult !== true) {
        $myError = $myError . $vresult;
      }

      if ($myError == "") {
        if (!$confirmSub) {

          $mailSender = &JFactory::getMailer();
          $mailSender->addRecipient($recipient);
          if ($sendingWithSetEmail) {
            $mailSender->setSender(array($fromEmail,$fromName));
          }
          else {
            $mailSender->setSender(array($_POST["nsp_email"],$_POST["nsp_name"]));
          }
          $mailSender->setSubject($subject);

          // insert into the database
          $mlists = '';
          if (isset($_POST["mailing_lists2"])) {
            $myposts = $_POST["mailing_lists2"];
            foreach($myposts as $mpost) {
              if ($mlists == '') {
                $mlists = $mpost;
              }
              else {
                $mlists = $mlists . ',' . $mpost;
              }
            }
          }
          else if (isset($_POST["mailing_lists"])) {
            $mlists = $_POST["mailing_lists"];
          }

          $myMessage = $myNameLabel . ' ' . htmlentities($_POST["nsp_name"]) . ', ' .
                       $myEmailLabel . ' ' . htmlentities($_POST["nsp_email"]) . ', ' .
                       date("r") . ', ' .
                       $mailing_list_label . ' ';
          $alllists = explode(',', $mlists);
          $myliststring = '';
          if (count($alllists)) {
            foreach($alllists as $alist) {
              if ($alist != '') {
                $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = 1 and `id` = "' . mysql_escape_string($alist) .'"';
                $db->setQuery($query);
                $tlist = $db->loadObject();
                if ($myliststring == '') {
                  $myliststring = $myliststring . $tlist->lname;
                }
                else {
                  $myliststring = $myliststring . ', ' . $tlist->lname;
                }
              }
            }
          }
          $myMessage = $myMessage . $myliststring;
          
          $myMessage .= "\n" . ExtraFieldsToString('plugin', 0);

          $mailSender->setBody($myMessage);

          $query = 'INSERT INTO `#__nspro_subs` (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.mysql_escape_string($_POST["nsp_name"]).'", "'.mysql_escape_string($_POST["nsp_email"]).'", "'.date("Y-m-d H:i:s").'", "1", "'.mysql_escape_string($mlists).'")';
          $db->setQuery($query);
          if (!$db->query()) {
            $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span>' . $br;
            $errors = $errors + 2;
          }
          else {
            // if inserted, save the extra fields.
            if ($vresult === true) {
              $saved = SaveExtraFields($db->insertid(), $_POST, true, 'plugin');
              if ($saved !== true) {
                $myReplacement = '<div class="nspro' . $classSuffix . '"><span style="color: '.$errorTextColor.';">' . $saved . '</span></div>';
                $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
              }
            }
            if ($mailSender->Send() !== true) {
              $myReplacement = '<span style="color: '.$errorTextColor.';">' . $errorText . '</span>';
              $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
            }
            else {
              $myReplacement = '<span style="color: '.$thanksTextColor.';">' . $pageText . '</span>';
              $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
            }
            if ($saveList) {
              $file = fopen($savePath, "a");
              if ($file !== false) {
                $mstring = str_replace('%n', htmlentities($_POST["nsp_name"]), $saveFormat);
                $mstring = str_replace('%e', htmlentities($_POST["nsp_email"]), $mstring);
                fwrite($file, $mstring);
                fclose($file);
              }
            }
          }

          if ($myError == '') {
            return true;
          }
        }
        else {
          $confirm_url = 'index.php?option=com_nspro&amp;view=nspro&amp;layout=confirm&amp;nss=nsplgp';
          $uri = & JURI::getInstance();
          $myBase = JURI::base();

          $myConfirmationLink = $myBase.$confirm_url.'&amp;u='.md5($_POST["nsp_email"]);

          $myMessage = str_replace('{conf_host}', $uri->getHost(), $messageConfirm);
          $myMessage = str_replace('{conf_url}', $myConfirmationLink, $myMessage);

          $myMessage = str_replace('{conf_link}', '<a href="' . $myConfirmationLink . '">', $myMessage);
          $myMessage = str_replace('{/conf_link}', '</a>', $myMessage);

          // insert into the database to be able to confirm
          $mlists = '';
          if (isset($_POST["mailing_lists2"])) {
            $myposts = $_POST["mailing_lists2"];
            foreach($myposts as $mpost) {
              if ($mlists == '') {
                $mlists = $mpost;
              }
              else {
                $mlists = $mlists . ',' . $mpost;
              }
            }
          }
          else if (isset($_POST["mailing_lists"])) {
            $mlists = $_POST["mailing_lists"];
          }

          $query = 'INSERT INTO `#__nspro_subs` (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.mysql_escape_string($_POST["nsp_name"]).'", "'.mysql_escape_string($_POST["nsp_email"]).'", "'.date("Y-m-d H:i:s").'", "0", "'.mysql_escape_string($mlists).'")';
          $db->setQuery($query);
          if (!$db->query()) {
            $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span>' . $br;
            $errors = $errors + 2;
          }
          else {
            // if inserted, save the extra fields.
            if ($vresult === true) {
              $saved = SaveExtraFields($db->insertid(), $_POST, true, 'plugin');
              if ($saved !== true) {
                $myReplacement = '<div class="nspro' . $classSuffix . '"><span style="color: '.$errorTextColor.';">' . $saved . '</span></div>';
                $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
              }
            }
            if (MySendMail($fromEmailConfirm, $fromNameConfirm, $_POST["nsp_email"], $subjectConfirm, $myMessage, true) !== true) {
              $myReplacement = '<span style="color: '.$errorTextColor.';">' . JText::_('Your subscription could not be completed') . '</span>';
            }
            else {
              $myReplacement = '<span style="color: '.$thanksTextColor.';">' . JText::_('An email has been sent to you to confirm your subscription') . '</span>';
            }
            $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
            return true;
          }

        }
      }
    }

    if ($recipient === "") {
      $myReplacement = '<span style="color: '.$errorTextColor.';">' . JText::_('No recipient specified') . '</span>';
      $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
      return true;
    }

    if ($recipient === "email@email.com") {
      $myReplacement = '<span style="color: '.$errorTextColor.';">'.JText::_('Mail Recipient is specified as email@email.com.'). $br .JText::_('Please change it from the Plugin parameters.').'</span>';
      $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);
      return true;
    }

    $myReplacement = "";

    if ($myError != "") {
      $myReplacement = $myError;
    }


    $db->setQuery('SELECT * FROM `#__nspro_fields` WHERE `published` = true ORDER BY `ordering`');
    $afields = $db->loadObjectList();

    $myReplacement = $myReplacement . '<div class="nspro' . $classSuffix . '"><form action="' . $url . '" method="post">' . "\n" .
                                      '<div class="nsprointro' . $classSuffix . '">'.$pre_text.'</div>' . "\n" .
                                      $table . "\n";
    if ($enable_anti_spam) {
      if ($anti_spam_position == 0) {
        $myReplacement = $myReplacement . $tr . $tdcolspan . $myAntiSpamQuestion . $ctd . $ctr . $tr . $emptycell . $td .'<input class="nspro inputbox ' . $classSuffix . '" type="text" name="nsp_anti_spam_answer" size="' . $nameWidth . '"/>' . $ctd . $ctr . "\n";
      }
    }
    // extra fields before form
    foreach($afields as $afield) {
      if (!$afield->abovepos) {
        continue;
      }
      if ($field_list == '1') {
        $fieldarray = explode(',', $fixed_fields);
        if (!in_array($afield->id, $fieldarray)) {
          continue;
        }
      }
      $val = '';
      if ($afield->fieldtype != '7') {
        $myReplacement .= $tr . $td;
        $myReplacement .= JText::_($afield->name);
        $myReplacement .= $separator;
        if (isset($_POST[$name_prefix.'field'.$afield->id])) {
          if (!FieldHadError($vresult, $afield->name)) {
            $val = $_POST[$name_prefix.'field'.$afield->id];
          }
        }
      }
      $fieldinput = GetFieldInputModulePlugin($afield, $val, $classSuffix, 'plugin', $text_field_width, $textarea_field_rows, $textarea_field_cols, $swidth);
      $myReplacement .= $fieldinput;
      if ($afield->fieldtype != '7') {
        $myReplacement .= $ctd . $ctr;
      }
    }
    $myReplacement = $myReplacement . $tr . $td . $myNameLabel . $separator . '<input class="nspro inputbox' . $classSuffix . '" type="text" name="nsp_name" maxlength="100" size="' . $nameWidth . '"';
    if (($errors & 1) != 1) {
      $myReplacement = $myReplacement . ' value="'.htmlentities($_POST["nsp_name"]).'"';
    }
    $myReplacement = $myReplacement . '/>' . $ctd . $ctr . "\n";
    $myReplacement = $myReplacement . $tr . $td . $myEmailLabel . $separator . '<input class="nspro inputbox' . $classSuffix . '" type="text" name="nsp_email" maxlength="200" size="' . $emailWidth . '"';
    if (($errors & 2) != 2) {
      $myReplacement = $myReplacement . ' value="'.htmlentities($_POST["nsp_email"]).'"';
    }
    $myReplacement = $myReplacement . '/>' . $ctd . $ctr . "\n";

    if ($show_select_list == 0) {
      $myReplacement = $myReplacement . '<input type="hidden" name="mailing_lists" value="' . $fixed_ids . '"/>';
    }
    else {
      $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = 1 ORDER BY `id`';
      $db->setQuery($query);
      $lists = $db->loadObjectList();
      if (count($lists) > 0) {
        $myReplacement = $myReplacement . $tr . $tdcolspan . $mailing_list_label . $ctd . $ctr;
        if ($show_select_list == 1) {
          $fixedlist = explode(',', $fixed_ids);
          foreach($lists as $list) {
            foreach($fixedlist as $fxlid) {
              if ($list->id == $fxlid) {
                $myReplacement = $myReplacement . $tr . $tdcolspan . '<input class="nspro inputbox' . $classSuffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . $ctd . $ctr;
              }
            }
          }
        }
        else {
          foreach($lists as $list) {
            $myReplacement = $myReplacement . $tr . $tdcolspan . '<input class="nspro inputbox' . $classSuffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . $ctd . $ctr;
          }
        }
      }
    }

    // extra fields after form
    foreach($afields as $afield) {
      if ($afield->abovepos) {
        continue;
      }
      if ($field_list == '1') {
        $fieldarray = explode(',', $fixed_fields);
        if (!in_array($afield->id, $fieldarray)) {
          continue;
        }
      }
      $val = '';
      if ($afield->fieldtype != '7') {
        $myReplacement .= $tr . $td;
        $myReplacement .= JText::_($afield->name);
        $myReplacement .= $separator;
        if (isset($_POST[$name_prefix.'field'.$afield->id])) {
          if (!FieldHadError($vresult, $afield->name)) {
            $val = $_POST[$name_prefix.'field'.$afield->id];
          }
        }
      }
      $fieldinput = GetFieldInputModulePlugin($afield, $val, $classSuffix, 'plugin', $text_field_width, $textarea_field_rows, $textarea_field_cols, $swidth);
      $myReplacement .= $fieldinput;
      if ($afield->fieldtype != '7') {
        $myReplacement .= $ctd . $ctr;
      }
    }

    if ($enable_anti_spam) {
      if ($anti_spam_position == 1) {
        $myReplacement = $myReplacement . $tr . $tdcolspan . $myAntiSpamQuestion . $ctd . $ctr . $tr . $emptycell . $td .'<input class="nspro inputbox ' . $classSuffix . '" type="text" name="nsp_anti_spam_answer" size="' . $nameWidth . '"/>' . $ctd . $ctr . "\n";
      }
    }
    $myReplacement = $myReplacement . $tr . $tdcolspan . '<input class="nspro button' . $classSuffix . '" type="submit" value="' . $buttonText . '" style="width: ' . $buttonWidth . '%;"/>' . $ctd . $ctr . "\n";
    $myReplacement = $myReplacement . $ctable . '</form></div>' . "\n";

    $text = str_replace('{newsletter_subscriber_pro}', $myReplacement, $text);


    return true;
  }

}